<template>
  <a-drawer
    :width="340"
    :mask-closable="false"
    :visible="dataModel.visible"
    unmount-on-close
    :ok-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel">
    <template #title>
      {{ dataModel.title }}
    </template>
    <div>
      <a-tree
        v-model:checked-keys="checkedKeys"
        :checkable="true"
        :check-strictly="true"
        :data="authorities"
        :field-names="{
           key: 'id'
        }"
      />
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref } from "vue";
import useDataModel from "@/hooks/data-model";
import useLoading from "@/hooks/loading";
import { treeList } from "@/api/modules/system/authority";
import { AuthorityVo } from "@/types/modules/system";
import { Operation } from "@/types/global";
import { findIdListByTenantId, grantAuthority } from '@/api/modules/system/tenant'
import { Message } from '@arco-design/web-vue'

const { dataModel, openModel, closeModel } = useDataModel();
const { loading, setLoading } = useLoading();
const tenantId = ref<string>('')
const checkedKeys = ref<number[]>([1, 2])
const authorities = ref<AuthorityVo[]>()

const grantAuthorities = async (id: string) => {
  setLoading(true)
  tenantId.value = id
  authorities.value = (await treeList()).data
  checkedKeys.value = (await findIdListByTenantId(id)).data
  openModel("分配租户权限", false, true, Operation.UPDATE);
  setLoading(false)
}

const handleCancel = () => {
  checkedKeys.value = [0]
  closeModel();
}

const handleOk = async () => {
  if (dataModel.submit) {
    setLoading(true)
    try {
      await grantAuthority(tenantId.value, checkedKeys.value)
      Message.success({
        content: "分配成功",
        duration: 2000
      });
    } finally {
      setLoading(false)
    }
  }
  handleCancel()
}

defineExpose({ grantAuthorities });
</script>

<script lang="ts">
export default {
  name: "TenantJoinsAuthority"
};
</script>

<style scoped>

</style>
